package org.bookie.model.test.framework;

import java.util.Locale;

import org.apache.hivemind.Registry;
import org.apache.hivemind.impl.DefaultClassResolver;
import org.apache.hivemind.impl.RegistryBuilder;
import org.apache.hivemind.impl.XmlModuleDescriptorProvider;
import org.apache.hivemind.util.ClasspathResource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class DBLessTCExtension extends Assert {
    
    protected static SessionFactory factory = null;
    
    private Session session = null;

	private Registry registry;
    
    @BeforeMethod
	protected void setUp() throws Exception {
    	registry = buildTestingRegistry();
        session = (Session) registry.getService(Session.class);
        
	}
    
    @AfterMethod
	protected void tearDown() throws Exception {
    	session.flush();
    	registry.cleanupThread();
    	registry.shutdown();
	}
	
    /**
     * Returns current session
     * 
     * @return Current hibernate session
     */
    public Session getSession() {
        return session;
    }
    
    /**
     * Flushes and closes the session
     */
    public void flushAndCloseSession(){
    	session.flush();
    	session.clear();
    	registry.cleanupThread();
    }
    
	/**
	 * Builds testing registry by including "/META-INF/test-hivemodule.xml" 
	 * apart from normal files
	 * 
	 * @return
	 */
	private Registry buildTestingRegistry() {
		RegistryBuilder builder = new RegistryBuilder();
		builder.addDefaultModuleDescriptorProvider();
		DefaultClassResolver defaultClassResolver = new DefaultClassResolver();
		ClasspathResource classpathResource = new ClasspathResource(defaultClassResolver, "/META-INF/test-hivemodule.xml");
		builder.addModuleDescriptorProvider(new XmlModuleDescriptorProvider(defaultClassResolver, classpathResource));
		Registry registry = builder.constructRegistry(Locale.getDefault());
		return registry;
	}
	    

}
